import axios, { AxiosRequestConfig } from 'axios'
import NProgress from 'nprogress'
import { useUserStore } from '@/store/user'
import type { IUserStore } from '@/types/store/userStoreType'
import { nextTick } from 'vue'
let userStore: IUserStore;

const baseURL = import.meta.env.VITE_APP_BASE_URL as string
nextTick(() => {
  userStore = useUserStore() as unknown as IUserStore
  if(userStore.token !== '') userStore.updateUserInfo()
})

const getToken = (): string => {
  return userStore?.token || localStorage.getItem('token') || ''
}

// 设置请求头和请求路径
axios.defaults.baseURL = baseURL
axios.defaults.timeout = 10000
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8'
axios.defaults.withCredentials = true
axios.interceptors.request.use(
  (config): AxiosRequestConfig<any> => {
    // const token = getToken()
    // if(token !== '') {
    //   //@ts-ignore
    //   config.headers.token = token
    // }
    return config
  },
  (error) => {
    return error
  }
)
// 响应拦截
axios.interceptors.response.use((res) => {
  if (res.data.code === 111) {
    sessionStorage.setItem('token', '')
    // token过期操作
  }
  return res
})

interface ResType<T> {
  code: number
  data: T
  result: T
  message: string
  err?: string
  [name: string]: any //本不想加这一行的，可惜接口实在太不规范，没办法
}
interface Http {
  get<T>(url: string, params?: unknown, cache?: boolean): Promise<ResType<T>>
  post<T>(url: string, params?: unknown, cache?: boolean): Promise<ResType<T>>
  upload<T>(url: string, params: unknown): Promise<ResType<T>>
  download(url: string): void
}

const http: Http = {  //cache为是否使用缓存.若不使用缓存，则在url上添加时间戳
  get(url, params, cache = false) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      if(!cache) url += `?t=${new Date().getTime()}`
      const token = getToken()
      if(token !== '' ) url += `&cookie=${encodeURIComponent(token)}`
      axios
        .get(url, { params })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params, cache = false) { //cache为是否使用缓存.若不使用缓存，则在url上添加时间戳
    return new Promise((resolve, reject) => {
      NProgress.start()
      if(!cache) url += `?t=${new Date().getTime()}`
      const token = getToken()
      // @ts-ignore
      if(token !== '' && params && typeof params === 'object') params.cookie = token
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  upload(url, file) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, file, {
          headers: { 'Content-Type': 'multipart/form-data' },
        })
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  download(url) {
    const iframe = document.createElement('iframe')
    iframe.style.display = 'none'
    iframe.src = url
    iframe.onload = function () {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  },
}
export default http